package abacab.serial;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import abacab.ActorSystem;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.typesafe.config.Config;

/**
 * A serializer using JSON
 */
public class JsonSerializer implements Serializer {
	/** The JSON serializer */
	private final Gson	gson;

	/**
	 * Create the serializer
	 * 
	 * @param config
	 *          the configuration
	 */
	public JsonSerializer(Config config) {
		GsonBuilder builder = new GsonBuilder();
		builder.setPrettyPrinting();
		this.gson = builder.create();
	}

	@Override
	public boolean isClassNameNeeded() {
		return true;
	}

	@Override
	public void encode(Object obj, OutputStream os) throws IOException {
		OutputStreamWriter writer = new OutputStreamWriter(os, ActorSystem.CHARSET);
		this.gson.toJson(obj, writer);
	}

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Object decode(InputStream is, Class clazz) throws IOException, ClassNotFoundException {
		InputStreamReader reader = new InputStreamReader(is, ActorSystem.CHARSET);
		return this.gson.fromJson(reader, clazz);
	}

	@Override
	public void dispose() {
		// nothing to do
	}
}